/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.base {

	/**
	 * @author Marek Brun
	 */
	public class MLActionClass extends MLBroadcastClass {
		
		public var event_ActionStart:String='ActionStart';
		public var event_ActionFinish:String='ActionFinish';
		public var event_RunningChanged:String='RunningChanged';		public var event_RunningFlagChanged:String='RunningFlaChanged';
		
		private var isRunning:Boolean;
		protected var isRunningFlag:Boolean;
		protected var _isSuccess:Boolean=false;
		
		public function MLActionClass() {
			isRunning=false;
			isRunningFlag=isRunning;
		}
		/*abstract*/ protected function doFinish():Boolean {
			
			return true;
		}
		/*abstract*/ protected function doStart():Boolean {
			
			return true;
		}
		
		public function get isSuccess():Boolean {
			return _isSuccess;
		}
		
		public function setIsRunningFlag(bool:Boolean):Boolean {
			if(isRunningFlag!=bool){
				isRunningFlag=bool;
				broadcastEvent(event_RunningFlagChanged);
				if(isRunningFlag){
					start();
				}else{
					finish();
				}
			}
			return isRunning;
		}
		
		public function getIsRunningFlag():Boolean {
			return isRunningFlag;
		}
		
		public function getIsRunning():Boolean {
			return isRunning;
		}
		
		public function setIsRunning(isActionStart:Boolean):void {
			if(isActionStart){ start(); }else{ finish(); }
		}
		
		public function start():Boolean {
			if(!isRunningFlag){ setIsRunningFlag(true); return isRunning; }
			if(isRunning){ return false; }
			if(!doStart()){ return false; }
			isRunning=true;
			_isSuccess=false;
			broadcastEvent(event_ActionStart);			broadcastEvent(event_RunningChanged);
			return true;
		}
		
		public function finish():Boolean {
			if(isRunningFlag){ setIsRunningFlag(false); return !isRunning; }
			if(!isRunning){ return false; }
			
			if(!doFinish()){ return false; }
			isRunning=false;
			
			broadcastEvent(event_ActionFinish);
			broadcastEvent(event_RunningChanged);
			return true;
		}
		
		override public function dispose():void {
			super.dispose();
		}
	}
}
